package com.alibaba.dubbo.remoting.msgcodec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream;
import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream;
import com.alibaba.dubbo.remoting.MessageDecode;
import com.alibaba.dubbo.remoting.MessageEncodeRegistry;

public class DecodeWrapper implements MessageDecode {
	
	private MessageDecode[] decoder;
	public DecodeWrapper(MessageDecode []decoder, boolean reverse){
		if(reverse){
			this.decoder = new MessageDecode[decoder.length];
			for(int  i = 0;i<decoder.length;i++){
				this.decoder[i] = decoder[decoder.length - 1 -i];
			}
		}else{
			this.decoder = new MessageDecode[decoder.length];
			for(int  i = 0;i<decoder.length;i++){
				this.decoder[i] = decoder[i];
			}
		}
	}
	
	public DecodeWrapper(MessageDecode []decoder){
		this(decoder, true);
	}

	@Override
	public int decode(InputStream in, OutputStream out/*, MessageEncodeRegistry registry*/) throws IOException {
		InputStream a = in;
		if(decoder.length > 1){
			UnsafeByteArrayOutputStream b = new UnsafeByteArrayOutputStream(4096);
			for(int i = 0;i < decoder.length-1;i++){
				decoder[i].decode(a, b/*, registry*/);
				a = new UnsafeByteArrayInputStream(b.detach());
				b.reset();
			}
		}
		return decoder[decoder.length -1].decode(a, out/*, registry*/);
	}
}
